<script lang="ts" setup>

const { t, locale } = useI18n();
import * as yup from 'yup';
import { Form } from 'vee-validate';
import type { EnumCurrencyKey } from '~/apis/types';
import type { CurrencyCode } from '~/composables/useCurrencyData';
interface Props {
  initCurrency: EnumCurrencyKey
}
defineOptions({
  name: 'Address',
})
enum SheetType {
  CURRENCY = 1,
  CHAIN
}
type BaseOption = {
  label: string
  value: string
}
type TWithdrawCurrencyList = availableCurrency & ISortedListItem
const route = useRoute()
const { currentCurrency, currentCurrencyCode, withdrawCurrencyList, runGetFinanceWithdrawCurrencyData } = useCurrencyData()
const props = defineProps<Props>()
const appStore = useAppStore()
const brandStore = useBrandStore()
const showSheet = ref(false)
const selectedCurrency = ref()
const curContractList = ref()
const virtualCurrencyList = ref()
const formRef = ref()
const setDefault = ref(false)
const { getVirtualCurrencyContractType } = useCurrencyData()
const currentNetwork = ref()/** 初始化的币种 */
const currency = ref(props.initCurrency)
const currency_code = ref(currencyConfig[props.initCurrency]?.cur)
const sheetType = ref<SheetType>(SheetType.CURRENCY)
// const { runMemberAuthConfig } = useAuthConfig()
/** 首次加载不展示子组件loading */

const schema = computed(() => yup.object().shape({
  address: yup.string().required(t('wallet_address_placeholder')).matches(virtualCoinAddressReg, t('wrong_format_address')),
  password: yup.string().required(t('money_password_placeholder'))
}));


definePageMeta({
    layout: 'header-back',
    title: 'account_management'
})

// 协议label
const currentNetworkLabel = computed(() => curContractList.value.find((a: BaseOption)  => a.value === currentNetwork.value)?.label ?? '')

function onVirCurrencyChange(item: BaseOption) {
  selectedCurrency.value = item
  showSheet.value = false
}

// 切换网络
function onNetworkChange(item: BaseOption) {
  currentNetwork.value = item.value
  showSheet.value = false
}

watch(withdrawCurrencyList, () => {
  if(withdrawCurrencyList.value?.length){
    virtualCurrencyList.value = withdrawCurrencyList.value.filter(a => application.isVirtualCurrency(a.currency_name)).map((b) => {
      return {
        ...b,
        label: b.currency_name as EnumCurrencyKey,
        value: b.currency_id as CurrencyCode,
      }
    })
    if(virtualCurrencyList.value?.length && route.query.currency_id)
      selectedCurrency.value = virtualCurrencyList.value.find((item: TWithdrawCurrencyList) => item.currency_id == route.query.currency_id)
    else
      selectedCurrency.value = virtualCurrencyList.value?.length ? virtualCurrencyList.value[0] : ''
  }
}, {
  immediate: true,
})

watch(selectedCurrency, () => {
  const currencyType = virtualCurrencyList.value.find((a: TWithdrawCurrencyList) => a.currency_id === selectedCurrency.value?.currency_id)?.currency_name
  curContractList.value = currencyType ? getVirtualCurrencyContractType(currencyType) : []
  //
  const network = getVirtualCurrencyContractType(selectedCurrency.value?.currency_name)
  if(route.query.contract_type && network?.length){
    currentNetwork.value = network.find(item => item.value === route.query.contract_type)?.value
  }else{
    currentNetwork.value = network ? network[0]?.value : ''
  }
})

/** 刷新账号数据和获取可取款货币列表 */
await application.allSettled([
  appStore.updateUserInfo(),
  brandStore.runAsyncBrandBaseDetail(),
  runGetFinanceWithdrawCurrencyData(),
  // runMemberAuthConfig(),
])

const {
  run: runMemberWalletInsert,
  loading: addWalletInsertLoading,
} = useRequest(ApiMemberWalletInsert, {
  onSuccess() {
    message.success(t('bind_success'))
  },
})

async function handleBindAddress() {
  const { values } = formRef.value
  runMemberWalletInsert({
    contract_type: Number(currentNetwork.value),
    currency_id: selectedCurrency.value?.value,
    address: values.address,
    is_default: setDefault.value ? 1 : 2,
    pay_password: values.password,
    auth_type: 2,
  })
}

</script>

<template>
  <div class="m-[1rem] p-[1rem] rounded-[.5rem] bg-bg-black-4 mb-[3.75rem]">
    <Form :validation-schema="schema" @submit="handleBindAddress" ref="formRef">
      <BaseInput  :label="t('withdraw_currency')" name="currency_name" :modelValue="selectedCurrency?.currency_name"  @click="showSheet = true; sheetType = SheetType.CURRENCY" type="select">
        <template v-slot:left-icon>
          <AppCurrencyIcon class="size-[1.25rem]" :currency-type="getCurrencyConfigByCode(selectedCurrency?.currency_id)?.['name']"/>
        </template>
      </BaseInput>
      <BaseInput class="mt-[1rem]" :label="t('recharge_choose_chain')" name="currentNetworkLabel" :modelValue="currentNetworkLabel"  @click="sheetType = SheetType.CHAIN; showSheet = true" type="select">
      </BaseInput>
      <BaseSheet
        v-model="showSheet"
        :title="sheetType === SheetType.CURRENCY ? t('recharge_choose_currency') : t('recharge_choose_chain')"
        :showSearch="sheetType === SheetType.CURRENCY"
        :filterKey="sheetType === SheetType.CURRENCY ? 'currency_name' : 'label'"
        :items="sheetType === SheetType.CURRENCY ? virtualCurrencyList : curContractList"
      >
        <template #default="{ item }: { item?: any }">
          <li
            class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
            :class="[sheetType === SheetType.CURRENCY ? 
            (item.currency_id === selectedCurrency.currency_id && 'bg-bg-black-4'):
            (item.value === currentNetwork && 'bg-bg-black-4')]"
            @click="sheetType === SheetType.CURRENCY ? onVirCurrencyChange(item) : onNetworkChange(item)"
          >
            <div class="flex items-center gap-[.1875rem]">
              <!-- 货币图标 -->
              <AppCurrencyIcon class="size-[1.25rem]" v-if="sheetType === SheetType.CURRENCY"
                :currency-type="getCurrencyConfigByCode(item.currency_id)?.['name']" />
              <span class="font-medium text-text-white-1 text-[1rem] ml-[.5rem]">{{ item.currency_name || item.label }}</span>
            </div>
            <span class="text-text-white-1 text-[1rem]" v-if="sheetType === SheetType.CURRENCY">{{ item.amount }}</span>
            <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]"
              v-if="sheetType === SheetType.CHAIN && item.value === currentNetwork"></div>
          </li>
        </template>
      </BaseSheet>
      <BaseInput class="mt-[1rem]" :label="t('wallet_address')" name="address" :placeholder="t('wallet_address_placeholder')">
      </BaseInput>
      <BaseInput class="mt-[1rem]" :label="t('money_password')" name="password" type="password" :placeholder="t('money_password_placeholder')">
      </BaseInput>
      <BaseCheckbox :checked="setDefault" @click="setDefault = !setDefault" :label="t('set_as_default_withdraw_account')" class="mt-[.75rem] mb-[1rem]"/>
      <!-- <AppRechargeTip :text="t('address_tip')"/> -->
      <BaseButton class="w-full h-[2.5rem] mt-[1rem]" html-type="submit">
        <span class="text-text-black-10 text-[.75rem] mr-[.25rem]">{{t('bind_withdraw_account_confirm')}}</span>
      </BaseButton>
    </Form>
  </div>
</template>

<style lang="scss"></style>
